/*
 * main.cpp
 *
 *  Created on: 2013-1-2
 *      Author: gaobo.benny
 */

#include <iostream>
#include <stdio.h>
#include "protocol.h"

using namespace std;
using namespace msgbuf;
using namespace protocol;

void readFile(const char *file, IoBuffer& buf) {
	byte tmp[1024];
	FILE *fp = fopen(file, "r");
	int cnt;
	do {
		cnt = fread(tmp, 1, 1024, fp);
		buf.put(tmp, 0, cnt);
	} while (cnt == 1024);
	fclose(fp);
}

void writeFile(const char *file, IoBuffer &buf) {
	FILE *fp = fopen(file, "w+");
	fwrite(buf.buffer(), buf.limit(), 1, fp);
	fclose(fp);
}

void test1(void) {
	IoBuffer src(1024);
	readFile("c:\\tmp\\1", src);
	src.flip();
	cout << "buffer size=" << src.limit() << endl;

	IoBuffer buf(1024);
	src.copy(buf, DECOMPRESS);
	buf.flip();
	cout << "decompressed size=" << buf.limit() << endl;

	ProtocolMessageBeanFactory *factory = ProtocolMessageBeanFactory::instance();
	BinaryMessageBeanFormat fmt(factory);
	fmt.setIoBuffer(&buf);

	AllType *allType = AllType::instance();
	AllType *mb = (AllType*) fmt.readBean("AllType", allType);
	cerr << "current=" << buf.current() << endl;
	mb->print(cout);

	buf.clear();
	fmt.readBean("AllType", mb);
	buf.flip();
	src.clear();
	buf.copy(src, COMPRESS);
	src.flip();
	writeFile("c:\\tmp\\2", src);
	mb->release();

	mb = (AllType*) fmt.read<AllType>(NULL, "AllType", dt_message);
	mb->print(cout);
	cerr << "second current=" << buf.current() << endl;
}

void test2(void) {
	IoBuffer src(1024);
	readFile("c:\\tmp\\1", src);
	src.flip();

	IoBuffer buf(1024);
	src.copy(buf, DECOMPRESS);
	buf.flip();

	ProtocolMessageBeanFactory *factory = ProtocolMessageBeanFactory::instance();
	BinaryMessageBeanFormat fmt(factory);
	fmt.setIoBuffer(&buf);

	clock_t begin = clock();
	for (int i = 0; i < 10000; ++i) {
//		cout << i << " buffer limit=" << buf.limit() << " current=" << buf.current() << endl;
		AllType *mb = (AllType*) fmt.read<AllType>(NULL, "AllType", dt_message);
//		mb->print(cout);

		buf.clear();
		fmt.writeBean(mb);
		buf.flip();

		mb->release();
//		cout << i << endl;
	}
	clock_t end = clock();
	cout << "spent=" << (end - begin) << endl;


}

int main(void) {
	test2();

	ProtocolMessageBeanFactory::instance()->pool()->print(cout);
}

